'use strict'

module.exports = app => {
  const { service, config } = app
  return async function (ctx, next) {
    let authToken = ctx.headers.authorization
    const url = ctx.request.url
    if (config.middlewareIgnore['jwt'].test(url)) {
      await next()
    } else {
      if (authToken) {
        authToken = authToken.substr(7)
        const verifyRes = await service.accessToken.verifyToken(authToken)
        if (verifyRes) { // 校验通过
          await next()
        } else {
          ctx.body = {
            code: 4001,
            msg: '登录状态已过期'
          }
        }
      } else {
        ctx.body = {
          code: 4002,
          msg: '请登录后再进行操作'
        }
      }
    }
  }
}